﻿
using iSun.Common;
using iSun.Model;
using iSun.Web.UI.Controls;
using iSun.BLL.Base;
using iSun.SYS.Library;
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;


namespace iSun.WebApp
{
    public partial class AutoLoadForm : EditUIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateUI();
        }

        private void CreateUI()
        {
            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            string action = this.GetStringFromQueryString("action", "");
            string strFormID = this.GetStringFromQueryString("formid", Guid.Empty.ToString());
            string id = this.GetStringFromQueryString("id", "");
            BaseEntity instance = iSun.Common.Globals.getEntity(strEntity) as BaseEntity;
            BaseBussnies bInstance = new BLL.Base.BaseBussnies(instance);
            BaseEntity entity = null;

            if (instance == null)
            {
                instance = new DataTableBaseEntity();
                ((DataTableBaseEntity)instance).TableName = strEntity;
                string[] strArrary = ((DataTableBaseEntity)instance).GetKey();
                if (strArrary != null)
                {
                    ((DataTableBaseEntity)instance).TableKey = strArrary[0];
                    ((DataTableBaseEntity)instance).KeyType = strArrary[1];
                }
                ((DataTableBaseEntity)instance).CreateDataTable();
                ((DataTableBaseEntity)instance).EntityJson = iSun.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);

                if (id != "") //有ID表示编辑
                {
                    entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = strEntity;
                    ((DataTableBaseEntity)entity).TableKey = ((DataTableBaseEntity)instance).TableKey;
                    ((DataTableBaseEntity)entity).KeyType = ((DataTableBaseEntity)instance).KeyType;
                    ((DataTableBaseEntity)entity).CreateDT(id);
                    ((DataTableBaseEntity)entity).EntityJson = iSun.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                }
                else
                {
                    //初始化ID值
                    KeyValue = instance.GetTableIdValue();
                    if (KeyValue == Guid.Empty.ToString()||String.IsNullOrEmpty(KeyValue) )
                    {
                        ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
                    }
                    ((DataTableBaseEntity)instance).EntityJson = iSun.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);
                    //KeyValue = instance.GetTableIdValue();
                }
            }
            else
            {
                //初始化ID值
                entity = bInstance.GetEntityById(id) as BaseEntity;
       
            }
 
            //获取
            if (instance != null)
            {
                object O = Globals.GetPropertyValue(instance, instance.GetTableId());
                Guid? _id = ((O) == null) ? null : O as Guid?;
                //初始化ID值
                if (_id == null || _id == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, instance.GetTableId(), Guid.NewGuid());
                }
            }
            this.EditTemplate.Text = CreateHtml(instance, entity);
            KeyValue = instance.GetTableIdValue();
            //if (KeyValue == Guid.Empty.ToString())
            //{
            //    ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
            //}
            //KeyValue =instance["ID"]; //instance.GetTableId();
            //用于定义相关数据绑定信息
            iSun.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>("FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'");
            IList<iSun.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitysByCondition<SysFieldItem>("FormID='" + strFormID + "' or TableName='" + strEntity + "'");
            //用于处理
            CreateUIData(dsList);
            if (FormEntity != null) {
                string details = FormEntity.DetailsJson;
                FormTemplate.Text = FormEntity.HtmlString;
                this.jSave.Text = ""; //CreateScript(list);
            }
            

            //this.jInitControl.Text = "";// InitControl(list);
            this.MasterID.Text = SetMasterID();
        }

        /// <summary>
        /// 行为参数
        /// </summary>
        public String Action
        {
            get
            {
                return this.GetStringFromQueryString("action", "");
            }

        }

        public String KeyValue
        {
            set;
            get;
        }
        /// <summary>
        /// 生成对应的下拉数据
        /// </summary>
        /// <param name="fieldList"></param>
        private void CreateUIData(IList<iSun.SYS.Library.SysFieldItem> fieldList)
        {
            this.jInitControl.Text = "";
            if (fieldList == null)
            {
                return;
            }
            StringBuilder strHtml = new StringBuilder("");
            foreach (var e in fieldList)
            {
                IList<Dictionary> list = null;
                if (e.DataSourceType.ToLower() == "json")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=" + e.DataSource + ";\r\n");
                    list = Globals.JSonToObject<IList<Dictionary>>(e.DataSource);
                    string str = "";
                    if (e.ControlsType == "select")
                    {
                        str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                    }
                    else
                    {
                        str = "createComboBox('" + e.FieldName + "', { itemSource: ds_" + e.FieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                    }
                    //string str= "$('#"+ e.FieldName+"').comBind(ds_"+e.FieldName+",\"ValueMember\",\"DisplayMember\");";
                    strHtml.Append(str);
                }
                if (e.DataSourceType.ToLower() == "sql")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(e.DataSource.Replace("[B]", "'"));
                    if (list != null)
                    {
                      strHtml.Append(Globals.ObjectToJSON(list)+";");

                      string str = "";
                      if (e.ControlsType == "select")
                      {
                          str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                      }
                      else
                      {
                          str = "createComboBox('" + e.FieldName + "', { itemSource: ds_" + e.FieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                      }
                      //string str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                      strHtml.Append(str);
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }

                }
                if (e.DataSourceType.ToLower() == "dic")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(string.Format("Exec [dbo].[sp_GetDicList] '{0}'", e.DataSource));
                    if (list != null)
                    {
                        strHtml.Append(Globals.ObjectToJSON(list) + ";");
                        string str="";
                        if (e.ControlsType == "select")
                        {
                          str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                        }else{
                           str = "createComboBox('"+e.FieldName+"', { itemSource: ds_"+ e.FieldName +", style: 'dropdown', autoComplete: 'local' });\r\n";
                        }
                        strHtml.Append(str);
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }
                }
                
                //return string.Format(strSControl, e.FieldName, strHtml.ToString(), width);
            }
            this.jInitControl.Text = strHtml.ToString();
        }
    }
}
